{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Copyright 2014 Brett Slatkin, Pearson Education Inc.\n",
    "#\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "\n",
    "# Preamble to mimick book environment\n",
    "import logging\n",
    "from pprint import pprint\n",
    "from sys import stdout as STDOUT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 1\n",
    "class GameState(object):\n",
    "    def __init__(self):\n",
    "        self.level = 0\n",
    "        self.lives = 4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 2\n",
    "state = GameState()\n",
    "state.level += 1  # Player beat a level\n",
    "state.lives -= 1  # Player had to try again"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 3\n",
    "import pickle\n",
    "state_path = 'game_state.bin'\n",
    "with open(state_path, 'wb') as f:\n",
    "    pickle.dump(state, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'lives': 3, 'level': 1}\n"
     ]
    }
   ],
   "source": [
    "# Example 4\n",
    "with open(state_path, 'rb') as f:\n",
    "    state_after = pickle.load(f)\n",
    "print(state_after.__dict__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 5\n",
    "class GameState(object):\n",
    "    def __init__(self):\n",
    "        self.level = 0\n",
    "        self.lives = 4\n",
    "        self.points = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'lives': 4, 'level': 0, 'points': 0}\n"
     ]
    }
   ],
   "source": [
    "# Example 6\n",
    "state = GameState()\n",
    "serialized = pickle.dumps(state)\n",
    "state_after = pickle.loads(serialized)\n",
    "print(state_after.__dict__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'lives': 3, 'level': 1}\n"
     ]
    }
   ],
   "source": [
    "# Example 7\n",
    "with open(state_path, 'rb') as f:\n",
    "    state_after = pickle.load(f)\n",
    "print(state_after.__dict__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 8\n",
    "assert isinstance(state_after, GameState)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 9\n",
    "class GameState(object):\n",
    "    def __init__(self, level=0, lives=4, points=0):\n",
    "        self.level = level\n",
    "        self.lives = lives\n",
    "        self.points = points"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 10\n",
    "def pickle_game_state(game_state):\n",
    "    kwargs = game_state.__dict__\n",
    "    return unpickle_game_state, (kwargs,)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 11\n",
    "def unpickle_game_state(kwargs):\n",
    "    return GameState(**kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 12\n",
    "import copyreg\n",
    "copyreg.pickle(GameState, pickle_game_state)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'lives': 4, 'level': 0, 'points': 1000}\n"
     ]
    }
   ],
   "source": [
    "# Example 13\n",
    "state = GameState()\n",
    "state.points += 1000\n",
    "serialized = pickle.dumps(state)\n",
    "state_after = pickle.loads(serialized)\n",
    "print(state_after.__dict__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 14\n",
    "class GameState(object):\n",
    "    def __init__(self, level=0, lives=4, points=0, magic=5):\n",
    "        self.level = level\n",
    "        self.lives = lives\n",
    "        self.points = points\n",
    "        self.magic = magic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'points': 1000, 'magic': 5, 'lives': 4, 'level': 0}\n"
     ]
    }
   ],
   "source": [
    "# Example 15\n",
    "state_after = pickle.loads(serialized)\n",
    "print(state_after.__dict__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 16\n",
    "class GameState(object):\n",
    "    def __init__(self, level=0, points=0, magic=5):\n",
    "        self.level = level\n",
    "        self.points = points\n",
    "        self.magic = magic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 17\n",
    "try:\n",
    "    pickle.loads(serialized)\n",
    "except:\n",
    "    logging.exception('Expected')\n",
    "else:\n",
    "    assert False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 18\n",
    "def pickle_game_state(game_state):\n",
    "    kwargs = game_state.__dict__\n",
    "    kwargs['version'] = 2\n",
    "    return unpickle_game_state, (kwargs,)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 19\n",
    "def unpickle_game_state(kwargs):\n",
    "    version = kwargs.pop('version', 1)\n",
    "    if version == 1:\n",
    "        kwargs.pop('lives')\n",
    "    return GameState(**kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'level': 0, 'magic': 5, 'points': 1000}\n"
     ]
    }
   ],
   "source": [
    "# Example 20\n",
    "copyreg.pickle(GameState, pickle_game_state)\n",
    "state_after = pickle.loads(serialized)\n",
    "print(state_after.__dict__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 21\n",
    "copyreg.dispatch_table.clear()\n",
    "state = GameState()\n",
    "serialized = pickle.dumps(state)\n",
    "del GameState\n",
    "class BetterGameState(object):\n",
    "    def __init__(self, level=0, points=0, magic=5):\n",
    "        self.level = level\n",
    "        self.points = points\n",
    "        self.magic = magic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 22\n",
    "try:\n",
    "    pickle.loads(serialized)\n",
    "except:\n",
    "    logging.exception('Expected')\n",
    "else:\n",
    "    assert False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'\\x80\\x03c__main__\\nGameState\\nq\\x00)'\n"
     ]
    }
   ],
   "source": [
    "# Example 23\n",
    "print(serialized[:25])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 24\n",
    "copyreg.pickle(BetterGameState, pickle_game_state)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'\\x80\\x03c__main__\\nunpickle_game_state\\nq\\x00}'\n"
     ]
    }
   ],
   "source": [
    "# Example 25\n",
    "state = BetterGameState()\n",
    "serialized = pickle.dumps(state)\n",
    "print(serialized[:35])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
